const FormData = require("form-data");
const fs = require("fs");
const path = require("path");
const http = require("http");
const https = require("https");
const url = require("url");
const buffer = require("buffer");
const randomstring = require("randomstring");
const axios = require("axios").default;
const util = require("util");

const Toolbox = require("./Toolbox");
const getCookie = require("./getCookie");
const my_user_agent = require("./user-agent");


const upload_url = "http://mp.tt.cn/upload?type=portrait";
const parsed_url = url.parse(upload_url);
/**
 * 
 * @param {String} full_path 
 * @returns {Promise<{ok:Boolean,msg:String,data:Array<{filename:String,url:String}> }>}
 */
function uploadSingleFile(full_path, size_limit = 1 * 1024 * 1024) {
  return new Promise(async (resolve) => {
    let o_stats = await Toolbox.getStats(full_path);
    if (!o_stats.ok) {
      return resolve({
        ok: false,
        msg: `can not get stats of ${full_path}:${o_stats.msg}`
      })
    }
    if (!(o_stats.stats.isFile())) {
      return resolve({
        ok: false,
        msg: `It is not a file :${full_path}`
      })
    }
    let file_size = o_stats.stats.size;

    /**
     * @todo 施工中....
     */
  })
}


/**
 * @param {String} extname
 * @returns {Promise<{url:String,ok:Boolean,msg:String}>}
 * @param {import("fs").ReadStream|String} stream 
 */
function uploadStream(stream, extname = ".txt") {
  return new Promise(async resolve => {
    let eastday_cookie = await getCookie.getCookie();
    if (!eastday_cookie) {
      return resolve({
        ok: false,
        url: "",
        msg: "Get cookie failed!No eastday_cookie "
      });
    }
    let form = new FormData;
    form.append("mediaHeadPicFile", stream, {
      filename: randomstring.generate() + extname
    });
    form.append("type", "portrait");
    let headers = {
      "User-Agent": my_user_agent.getUserAgent(),
      "Cookie": eastday_cookie
    };
    form.on("error", (err) => {
      resolve({
        ok: false,
        msg: err.message,
        url: ""
      })
    })
    form.submit({
      host: parsed_url.host,
      path: parsed_url.path,
      protocol: parsed_url.protocol,
      headers: headers
    }, (err, res) => {
      if (err) {
        // console.error(err);
        return resolve({
          ok: false,
          msg: err.message,
          url: ""
        });
      }
      if (res.statusCode != 200) {
        return resolve({
          ok: false,
          msg: `HTTP ${res.statusCode} ${res.statusMessage}`,
          url: ""
        });
      }
      if ((!res.headers['content-type']) || res.headers['content-type'].indexOf("json") == -1) {
        return resolve({
          ok: false,
          msg: `Response content-type is ${res.headers['content-type']}`,
          url: ""
        });
      }
      let buf = new buffer.Buffer("");
      res.on("data", chunk => {
        buf += chunk;
      });
      res.on("end", () => {
        try {
          let obj = JSON.parse(buf);
          let src = obj['src'];
          if ((!src) || src == "undefined") {
            return resolve({
              ok: false,
              msg: `obj['src'] is ${obj['src']},and obj is ${buf}`
            })
          }
          // console.log(path.basename(full_path));
          let fullurl = `http://mp.tt.cn` + src
          // console.log(fullurl);
          resolve({
            ok: true,
            url: fullurl,
            msg: "ok"
          })
        } catch (e) {
          resolve({
            ok: false,
            msg: e,
            url: ""
          })
        }
      })
    });
  });
}



/**
 * @param {Number} x
 * @param {String} full_path 
 * @returns {Promise<{ok:Boolean,msg:String[],url:String}>}
 */
function uploadSingleForXTime(x, full_path) {
  let g = (function* () {
    for (let i = 1; i <= x; i++) {
      yield uploadSingleFile(full_path);
    }
  })();
  let it = g.next();
  let error_messages = [];
  return new Promise((resolve) => {
    (function bootstrap() {
      if (it.done) {
        resolve({
          ok: false,
          msg: error_messages,
          url: ""
        })
      } else {
        it.value.then((s) => {
          if (s.ok) {
            resolve({
              ok: true,
              msg: ['ok'],
              url: s.url
            });
          } else {
            error_messages.push(s.msg);
            it = g.next();
            setTimeout($ => bootstrap(), 2000);
          }
        })
      }
    })();
  })
}

if (!module.parent) {
  uploadSingleFile(path.join(__dirname, "../tmp/0.99GB[SUBPIG]×[TMBS][Final Life EP06][WEB].mp4"))
}

module.exports = {
  uploadSingle: uploadSingleFile,
  uploadSingleForXTime: uploadSingleForXTime,
  uploadStream: uploadStream
}